#include "editItemDialog.h"
#include "ui_editItemDialog.h"

//NoteItemMap _gItemMap;

editItemDialog::editItemDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::editItemDialog)
{
    ui->setupUi(this);
    ui->checkBox_Clock->setTristate(false);//This property holds whether the checkbox is a tri-state checkbox.
    bNote = true;
    setUIenabled(false);//disabled UI
    _pItemMap = new NoteItemMap;
    readFromFile();//init itemMap data

    updateUI();

    connect(ui->checkBox_Clock,SIGNAL(stateChanged(int)),this,SLOT(slotSetEnableComboBoxClocker(int)));
    connect(ui->checkBox_Note,SIGNAL(stateChanged(int)),this,SLOT(slotSetEnableComboBoxNote(int)));
    connect(ui->checkBox_Task,SIGNAL(stateChanged(int)),this,SLOT(slotSetEnableComboBoxTask(int)));

    connect(ui->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(updateUI(QListWidgetItem*)));
    connect(ui->spinBox_Progress,SIGNAL(valueChanged(int)),this,SLOT(slotUpdateProgress(int)));

    connect(ui->pushButton_New,SIGNAL(clicked()),this,SLOT(slotNewItem()));
    connect(ui->pushButton_Edit,SIGNAL(clicked()),this,SLOT(slotEditItem()));
    connect(ui->pushButton_Delete,SIGNAL(clicked()),this,SLOT(slotDeleteItem()));
    connect(ui->pushButton_Save,SIGNAL(clicked()),this,SLOT(slotSave()));

    connect(ui->pushButton_Close,SIGNAL(clicked()),this,SLOT(slotClose()));
}

editItemDialog::~editItemDialog()
{
    delete ui;
    SAFE_DELETE_POINTER(_pItemMap);
}

//************Public Functions***************************************************
NoteItemMap * editItemDialog::getItemMap()
{
    return _pItemMap;
}

NoteItemOneDay * editItemDialog::getItemOneday(QDate _date)
{//return specified date's item data
    setItemOneDay(_date);
    return &_itemOneDay;
}
void editItemDialog::setItemOneDay(NoteItemOneDay _items)
{
    _itemOneDay = _items;
}

void editItemDialog::setItemOneDay(QDate _date)
{
    if(!_pItemMap->getItemOneDay(_date,_itemOneDay))
        return;
}

void editItemDialog::setDate(QDate _date)
{//set dateEdit to current date
    ui->dateEdit->setDate(_date);
    ui->timeEdit->setTime(QTime::currentTime());
    ui->timeEdit_ClockTime->setTime(QTime::currentTime());
    _curDate_ItemOneDay = _date;
}

void editItemDialog::synchronismData()
{
    if(0 != _itemOneDay.getSize())
        _pItemMap->addItemOneDay(_itemOneDay);
    else
        _pItemMap->deleteItemOneDay(_curDate_ItemOneDay);
}

bool editItemDialog::readFromFile(QString fileName)
{//read notes data from file
    QString path = QDir::currentPath();
    path = path + "/" +fileName;
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly))
    {//can not open file
        //QIcon icon(":/images/warning.png");
        QMessageBox(QMessageBox::Warning,QString::fromUtf8("Warning"),QString::fromUtf8("Cannot Open File(noteData.ldc)"));
        return false;
    }

    QDataStream in(&file);
    in.setVersion(QDataStream::Qt_4_7);//binary version

    qint32 curVersion;
    in>>curVersion;

    _pItemMap->clear();

    switch(curVersion)
    {
        case 1:
        while(!in.atEnd())
        {//read each itemOneDay
            _itemOneDay.clear();
            QDate _date;
            qint32 _count;
            in>>_date>>_count;
            for(qint32 idx=0;idx<_count;++idx)
            {//there are _count items in current day
                qint32   _type;
                NoteType _itType;
                QDate   _itDate;
                QTime   _itTime;
                QString _itTitle;
                qint32  _itProgress;
                bool    _itBclock;
                QTime   _itClockTime;
                QString _itRemark;
                QStringList _itReceiver;
                in>>_type>>_itDate>>_itTime>>_itTitle>>_itProgress>>_itBclock>>_itClockTime>>_itRemark>>_itReceiver;
                _itType = (NoteType)_type;

                NoteItem _item(_itType,_itDate,_itTime,_itTitle,_itProgress,_itBclock,_itClockTime,_itRemark,_itReceiver);
                _itemOneDay.addItem(_item);
            }
            _pItemMap->addItemOneDay(_itemOneDay);
        }
        break;
    default:break;

    }

    file.close();
    return true;
}

void editItemDialog::saveToFile(QString fileName)
{//save notes data to file
    QString path = QDir::currentPath();
    path = path + "/" +fileName;
    QFile file(path);
    file.open(QIODevice::WriteOnly);

    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_4_7);//binary version
    out<<CURRENT_VERSION;//current version of the software

    QMap<QString,NoteItemOneDay>::const_iterator iterMap = _pItemMap->constBegin();
    for(;iterMap!=_pItemMap->constEnd();++iterMap)
    {//save each itemOneDay
        QDate _date = QDate::fromString(iterMap.key());
        NoteItemOneDay _itemOneDayTemp = iterMap.value();
        qint32 _count = _itemOneDayTemp.getSize();
        out<<_date<<_count;

        QMap<QString,NoteItem>::const_iterator iterOneday = _itemOneDayTemp.constBegin();
        for(qint32 idx=0;idx<_count;++idx,++iterOneday)
        {//there are _count items in current day
            NoteItem _item = iterOneday.value();
            NoteType _itType    = _item.getNoteType();
            qint32   _type = (qint32)_itType;
            QDate   _itDate     = _item.getDate();
            QTime   _itTime     = _item.getTime();
            QString _itTitle    = _item.getTitle();
            qint32  _itProgress = _item.getProgress();
            bool    _itBclock   = _item.getClocker();
            QTime   _itClockTime= _item.getClockTime();
            QString _itRemark   = _item.getRemark();
            QStringList _itReceiver = _item.getReceiver();
            out<<_type<<_itDate<<_itTime<<_itTitle<<_itProgress<<_itBclock<<_itClockTime<<_itRemark<<_itReceiver;
        }
    }
    file.close();
}

//************Private Slots***************************************************
void editItemDialog::slotSetEnableComboBoxClocker(int)
{
    //if(ui->checkBox_Clock->isChecked())
    bool bVisible = ui->checkBox_Clock->isChecked();
    ui->timeEdit_ClockTime->setVisible(bVisible);
    ui->timeEdit_ClockTime->setTime(ui->timeEdit->time());
}

void editItemDialog::slotSetEnableComboBoxNote(int)
{
    bNote = ui->checkBox_Note->isChecked();//is current item a note or task?true
    ui->checkBox_Task->setChecked(!bNote);//if checkBox_Note is checked , make checkBox_Task false
}

void editItemDialog::slotSetEnableComboBoxTask(int)
{
    bNote = !ui->checkBox_Task->isChecked();//is current item a note or task?true
    ui->checkBox_Note->setChecked(bNote);
}

void editItemDialog::slotNewItem()
{
    _state = NEW;
    initUI();
    setUIenabled(true);
}

void editItemDialog::slotEditItem()
{
    _state = EDIT;
    QList<QListWidgetItem*> list = ui->listWidget->selectedItems();
    if(list.isEmpty())
    {
        QMessageBox(QMessageBox::Warning,QString::fromUtf8("Warning"),QString::fromUtf8("Please Select The Item to Delete!"));
        return;
    }
    else
    {
        QList<QListWidgetItem*>::iterator iter = list.begin();
        updateUI(*iter);
        QString title = (*iter)->text();
        _itemTemp = _itemOneDay.getItemByTitle(title);//save current item in _itemTemp temporarily
        _itemOneDay.deleteItemByTitle(title);//delete current item.
        synchronismData();
        setUIenabled(true);
    }
}

void editItemDialog::slotDeleteItem()
{
    QList<QListWidgetItem*> list = ui->listWidget->selectedItems();
    if(list.isEmpty())
    {
        QMessageBox(QMessageBox::Warning,QString::fromUtf8("Warning"),QString::fromUtf8("Please Select The Item to Delete!"));
        return;
    }
    else
    {
        QList<QListWidgetItem*>::iterator iter = list.begin();
        _itemOneDay.deleteItemByTitle((*iter)->text());
        synchronismData();
        saveToFile();
        updateUI();
        emit updateDesktop();
    }
}

void editItemDialog::slotSave()
{
    if(!ui->textEdit_Title->toPlainText().isEmpty())
    {
        NoteItem tempItem;
        tempItem.clear();
        if(ui->checkBox_Note->isChecked())
            tempItem.setNoteType(NOTE);
        else
            tempItem.setNoteType(TASK);
        tempItem.setDate(ui->dateEdit->date());
        tempItem.setTime(ui->timeEdit->time());
        tempItem.setTitle(ui->textEdit_Title->toPlainText());
        tempItem.setProgress(ui->spinBox_Progress->value());
        tempItem.setClocker(ui->checkBox_Clock->isChecked());
        tempItem.setClockTime(ui->timeEdit_ClockTime->time());
        tempItem.setRemark(ui->textEdit_Remark->toPlainText());

        _itemOneDay.addItem(tempItem);
        synchronismData();
        saveToFile();
    }
    updateUI();
    setUIenabled(false);
    emit updateDesktop();
}

void editItemDialog::setUIenabled(bool flag)
{
    ui->dateEdit->setEnabled(flag);
    ui->timeEdit->setEnabled(flag);
    ui->textEdit_Title->setEnabled(flag);
    ui->textEdit_Remark->setEnabled(flag);
    ui->checkBox_Clock->setEnabled(flag);
    ui->timeEdit_ClockTime->setEnabled(flag);
    ui->spinBox_Progress->setEnabled(flag);
}

void editItemDialog::initUI()
{
    ui->checkBox_Note->setChecked(true);
    ui->checkBox_Task->setChecked(false);
    ui->textEdit_Title->clear();
    ui->textEdit_Remark->clear();
    ui->spinBox_Progress->setValue(0);
    ui->checkBox_Clock->setChecked(true);
    ui->timeEdit->setTime(QTime::currentTime());
    ui->timeEdit_ClockTime->setTime(QTime::currentTime());
    ui->progressBar->setValue(0);

    setUIenabled(false);
}

void editItemDialog::updateUI()
{
    ui->listWidget->clear();
    QMap<QString,NoteItem>::const_iterator iter = _itemOneDay.constBegin();
    for(; iter!=_itemOneDay.constEnd();++iter)
        ui->listWidget->addItem(((NoteItem)iter.value()).getTitle());

    initUI();
}

void editItemDialog::updateUI(QListWidgetItem * selectedItem)
{
    NoteItem tempItem = _itemOneDay.getItemByTitle(selectedItem->text());
    updateUI(tempItem);
}

void editItemDialog::updateUI(NoteItem _item)
{
    //update data
    if(NOTE == _item.getNoteType())
    {
        ui->checkBox_Note->setChecked(true);;
        ui->checkBox_Task->setChecked(false);
    }
    else
    {
        ui->checkBox_Note->setChecked(false);;
        ui->checkBox_Task->setChecked(true);
    }
    ui->dateEdit->setDate(_item.getDate());
    ui->timeEdit->setTime(_item.getTime());
    ui->textEdit_Title->setPlainText(_item.getTitle());
    ui->textEdit_Remark->setPlainText(_item.getRemark());
    ui->checkBox_Clock->setChecked(_item.getClocker());
    ui->timeEdit_ClockTime->setTime(_item.getClockTime());
    ui->spinBox_Progress->setValue(_item.getProgress());
    ui->progressBar->setValue(_item.getProgress());

    //set these widget disabled
    setUIenabled(false);

}

void editItemDialog::slotUpdateProgress(int)
{
    ui->progressBar->setValue(ui->spinBox_Progress->value());
}

void editItemDialog::slotClose()
{
    if(EDIT == _state)
    {
        _itemOneDay.addItem(_itemTemp);
        synchronismData();
    }

    reject();
}
